import { May } from "../type"
import { TaskStatus } from "./TaskProcess"

export default class Chunk {
  constructor(value: Blob, offset: number) {
    this._value = value
    this._offset = offset
    this.controller = new AbortController()
  }

  _upload: any
  private _value: any
  private _offset: number
  controller: AbortController
  private _prev: May<Chunk>
  private _next: May<Chunk>
  private _status: TaskStatus = "ready"
  private _response?: any
  private _error?: any
  get response() {
    return this._response
  }
  get offset() {
    return this._offset
  }
  get status() {
    return this._status
  }

  set status(val: TaskStatus) {
    this._status = val
  }
  get prev(): May<Chunk> {
    return this._prev
  }

  set prev(val: May<Chunk>) {
    this._prev = val
  }
  get next(): May<Chunk> {
    return this._next
  }

  set next(val: Chunk) {
    this._next = val
  }
  get value() {
    return this._value
  }
  get error() {
    return this._error
  }
  set error(val: TaskStatus) {
    this._error = val
  }

  async upload(run?: any) {
    this.status = "pending"
    try {
      const res = await run?.(this)
      this.status = "success"
    } catch (e: any) {
      this.status = "error"
      this.error = e
      //错误抛出错误及自身
      throw [e, this]
    }
  }

  async abort() {
    this.controller.abort()
  }
}
